/*
 * // +-------------------------------------------------------------------------------------------------
 * // |                 有你就好 [ 有节骨乃坚，无心品自端 ]     <http://encoding.wang>
 * // +-------------------------------------------------------------------------------------------------
 * // |                             独在异乡为异客         每逢佳节倍思亲
 * // +-------------------------------------------------------------------------------------------------
 * // |                 联系:   <707069100@qq.com>      <http://weibo.com/513778937>
 * // +-------------------------------------------------------------------------------------------------
 */

// -----------------------------------------------------------------------------------------------------
// +----------------------------------------------------------------------------------------------------
// |                   ErYang出品 属于小极品          共同学习    共同进步
// +----------------------------------------------------------------------------------------------------
// -----------------------------------------------------------------------------------------------------


package wang.encoding.mroot.admin.controller.system.role


import com.alibaba.fastjson.JSONObject
import com.baomidou.mybatisplus.plugins.Page
import org.apache.shiro.authz.annotation.RequiresPermissions
import org.slf4j.Logger
import org.slf4j.LoggerFactory
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.web.bind.annotation.PathVariable
import org.springframework.web.bind.annotation.RequestMapping
import org.springframework.web.bind.annotation.ResponseBody
import org.springframework.web.bind.annotation.RestController
import org.springframework.web.servlet.ModelAndView
import org.springframework.web.servlet.mvc.support.RedirectAttributes
import wang.encoding.mroot.admin.common.controller.BaseAdminController
import wang.encoding.mroot.admin.common.util.ShiroSessionUtil
import wang.encoding.mroot.common.annotation.FormToken
import wang.encoding.mroot.common.annotation.RequestLogAnnotation
import wang.encoding.mroot.common.business.ResultData
import wang.encoding.mroot.common.constant.RequestLogConstant
import wang.encoding.mroot.common.exception.ControllerException
import wang.encoding.mroot.common.util.ArrayUtil
import wang.encoding.mroot.model.entity.system.Role
import wang.encoding.mroot.model.entity.system.Rule
import wang.encoding.mroot.model.entity.system.User
import wang.encoding.mroot.model.enums.StatusEnum
import wang.encoding.mroot.service.system.RoleService
import wang.encoding.mroot.service.system.RuleService
import java.math.BigInteger
import javax.servlet.http.HttpServletRequest


/**
 * 后台 角色 控制器
 *
 *@author ErYang
 */
@RestController
@RequestMapping(value = ["/role"])
class RoleController : BaseAdminController() {


    @Autowired
    private lateinit var roleService: RoleService

    @Autowired
    private lateinit var ruleService: RuleService


    companion object {

        /**
         * logger
         */
        private val logger: Logger = LoggerFactory.getLogger(RoleController::class.java)
        /**
         * 模块
         */
        private const val MODULE_NAME = "/role"

        /**
         * 视图目录
         */
        private const val VIEW_PATH: String = "/system/role"

        /**
         * 对象名称
         */
        private const val VIEW_MODEL_NAME: String = "role"
        /**
         * 首页
         */
        private const val INDEX: String = "/index"
        private const val INDEX_URL: String = MODULE_NAME + INDEX
        private const val INDEX_VIEW: String = VIEW_PATH + INDEX
        /**
         * 新增
         */
        private const val ADD: String = "/add"
        private const val ADD_URL: String = MODULE_NAME + ADD
        private const val ADD_VIEW: String = VIEW_PATH + ADD
        /**
         * 保存
         */
        private const val SAVE: String = "/save"
        private const val SAVE_URL: String = MODULE_NAME + SAVE
        /**
         * 修改
         */
        private const val EDIT: String = "/edit"
        private const val EDIT_URL: String = MODULE_NAME + EDIT
        private const val EDIT_VIEW: String = VIEW_PATH + EDIT
        /**
         * 更新
         */
        private const val UPDATE: String = "/update"
        private const val UPDATE_URL: String = MODULE_NAME + UPDATE
        /**
         * 查看
         */
        private const val VIEW: String = "/view"
        private const val VIEW_URL: String = MODULE_NAME + VIEW
        private const val VIEW_VIEW: String = VIEW_PATH + VIEW
        /**
         * 删除
         */
        private const val DELETE: String = "/delete"
        private const val DELETE_URL: String = MODULE_NAME + DELETE
        private const val DELETE_BATCH: String = "/deleteBatch"
        private const val DELETE_BATCH_URL: String = MODULE_NAME + DELETE_BATCH
        /**
         * 授权
         */
        private const val AUTHORIZATION: String = "/authorization"
        private const val AUTHORIZATION_URL: String = MODULE_NAME + AUTHORIZATION
        private const val AUTHORIZATION_VIEW: String = VIEW_PATH + AUTHORIZATION
        /**
         * 保存授权
         */
        private const val AUTHORIZATION_SAVE: String = "/authorizationSave"
        private const val AUTHORIZATION_SAVE_URL: String = MODULE_NAME + AUTHORIZATION_SAVE

        /**
         * 回收站
         */
        private const val RECYCLE_BIN_INDEX: String = "/recycleBin"
        private const val RECYCLE_BIN_INDEX_URL: String = MODULE_NAME + RECYCLE_BIN_INDEX
        private const val RECYCLE_BIN_INDEX_VIEW: String = VIEW_PATH + RECYCLE_BIN_INDEX
        /**
         * 恢复
         */
        private const val RECOVER: String = "/recover"
        private const val RECOVER_URL: String = MODULE_NAME + RECOVER

        private const val RECOVER_BATCH: String = "/recoverBatch"
        private const val RECOVER_BATCH_URL: String = MODULE_NAME + RECOVER_BATCH

    }

    // -------------------------------------------------------------------------------------------------

    /**
     * 列表页面
     *
     * @param request HttpServletRequest
     * @return ModelAndView
     */
    @RequiresPermissions(value = [INDEX_URL])
    @RequestMapping(INDEX)
    @RequestLogAnnotation(module = RequestLogConstant.ADMIN_MODULE,
            title = RequestLogConstant.ADMIN_MODULE_ROLE_INDEX)
    @Throws(ControllerException::class)
    fun index(request: HttpServletRequest): ModelAndView {
        val modelAndView = ModelAndView(super.initView(INDEX_VIEW))
        super.initViewTitleAndModelUrl(INDEX_URL, MODULE_NAME, request)

        val role = Role()
        val title: String? = request.getParameter("title")
        if (null != title && title.isNotBlank()) {
            role.title = title
            modelAndView.addObject("title", title)
        }
        role.status = StatusEnum.NORMAL.key
        val page: Page<Role> = roleService.list2page(super.initPage(request), role, Role.ID, false)!!
        modelAndView.addObject(VIEW_PAGE_NAME, page)
        return modelAndView
    }

    // -------------------------------------------------------------------------------------------------

    /**
     * 添加页面
     *
     * @param request HttpServletRequest
     * @return ModelAndView
     */
    @RequiresPermissions(value = [ADD_URL])
    @RequestMapping(ADD)
    @RequestLogAnnotation(module = RequestLogConstant.ADMIN_MODULE,
            title = RequestLogConstant.ADMIN_MODULE_ROLE_ADD)
    @FormToken(init = true)
    @Throws(ControllerException::class)
    fun add(request: HttpServletRequest): ModelAndView {
        val modelAndView = ModelAndView(super.initView(ADD_VIEW))
        super.initViewTitleAndModelUrl(ADD_URL, MODULE_NAME, request)
        // 最大排序值
        val maxSort: Int = roleService.getMax2Sort() + 1
        modelAndView.addObject("maxSort", maxSort)
        // 设置上个请求地址
        super.initRefererUrl(request)
        return modelAndView
    }

    // -------------------------------------------------------------------------------------------------

    /**
     * 处理保存
     *
     * @param request HttpServletRequest
     * @param role Role
     * @return ModelAndView
     */
    @RequiresPermissions(value = [SAVE_URL])
    @RequestMapping(SAVE)
    @RequestLogAnnotation(module = RequestLogConstant.ADMIN_MODULE,
            title = RequestLogConstant.ADMIN_MODULE_ROLE_SAVE)
    @FormToken(remove = true)
    @Throws(ControllerException::class)
    fun save(request: HttpServletRequest, role: Role): Any {
        if (httpRequestUtil.isAjaxRequest(request)) {
            val failResult: ResultData = ResultData.fail()

            // 创建 Role 对象
            val saveRole: Role = this.initAddData(request, role)

            // Hibernate Validation  验证数据
            val validationResult: String? = roleService.validationRole(saveRole)
            if (null != validationResult && validationResult.isNotBlank()) {
                return super.initErrorHibernateValidationJSONObject(failResult, validationResult)
            }

            // 验证数据唯一性
            val flag: Boolean = this.validationAddData(saveRole, failResult)
            if (!flag) {
                return super.initErrorValidationJSONObject(failResult)
            }

            // 新增角色 id
            val id: BigInteger? = roleService.saveBackId(saveRole)
            return super.initSaveJSONObject(id)
        } else {
            return super.initErrorRedirectUrl()
        }
    }

    // -------------------------------------------------------------------------------------------------

    /**
     * 编辑页面
     *
     * @param id String
     * @param request HttpServletRequest
     * @param redirectAttributes RedirectAttributes
     * @return ModelAndView
     */
    @RequiresPermissions(value = [EDIT_URL])
    @RequestMapping("$EDIT/{id}")
    @RequestLogAnnotation(module = RequestLogConstant.ADMIN_MODULE,
            title = RequestLogConstant.ADMIN_MODULE_ROLE_EDIT)
    @FormToken(init = true)
    @Throws(ControllerException::class)
    fun edit(@PathVariable(ID_NAME) id: String, request: HttpServletRequest,
             redirectAttributes: RedirectAttributes): ModelAndView {
        val modelAndView = ModelAndView(super.initView(EDIT_VIEW))

        super.initViewTitleAndModelUrl(EDIT_URL, MODULE_NAME, request)
        val idValue: BigInteger? = super.getId(id)
        if (null == idValue || BigInteger.ZERO > idValue) {
            return initValidationResult2Get(modelAndView, redirectAttributes, INDEX_URL)
        }
        // 数据真实性
        val role: Role? = roleService.getById(idValue)
                ?: return initValidationResult2Get(modelAndView, redirectAttributes, INDEX_URL)
        if (StatusEnum.DELETE.key == role!!.status) {
            return initValidationResult2Get(modelAndView, redirectAttributes, INDEX_URL)
        }
        modelAndView.addObject(VIEW_MODEL_NAME, role)

        // 设置上个请求地址
        super.initRefererUrl(request)
        return modelAndView
    }

    // -------------------------------------------------------------------------------------------------

    /**
     * 处理更新
     *
     * @param request HttpServletRequest
     * @param role Role
     * @return ModelAndView
     */
    @RequiresPermissions(value = [UPDATE_URL])
    @RequestMapping(UPDATE)
    @RequestLogAnnotation(module = RequestLogConstant.ADMIN_MODULE,
            title = RequestLogConstant.ADMIN_MODULE_ROLE_UPDATE)
    @FormToken(remove = true)
    @Throws(ControllerException::class)
    fun update(request: HttpServletRequest, role: Role): Any {
        if (httpRequestUtil.isAjaxRequest(request)) {
            val failResult: ResultData = ResultData.fail()
            // 验证数据
            val idValue: BigInteger? = super.getId(request)
            if (null == idValue || BigInteger.ZERO > idValue) {
                return super.initErrorCheckJSONObject(failResult)
            }
            // 数据真实性
            val roleBefore: Role = roleService.getById(idValue)
                    ?: return super.initErrorCheckJSONObject(failResult)
            if (StatusEnum.DELETE.key == roleBefore.status) {
                return super.initErrorCheckJSONObject(failResult)
            }


            // 创建 Role 对象
            var editRole: Role = Role.copy2New(role)
            editRole.id = roleBefore.id
            val statusStr: String? = super.getStatusStr(request)
            when {
                statusStr.equals(configProperties.bootstrapSwitchEnabled) -> editRole.status = StatusEnum.NORMAL.key
                null == statusStr -> editRole.status = StatusEnum.DISABLE.key
                else -> editRole.status = StatusEnum.DISABLE.key
            }
            editRole = this.initEditData(editRole)

            // Hibernate Validation 验证数据
            val validationResult: String? = roleService.validationRole(editRole)
            if (null != validationResult && validationResult.isNotBlank()) {
                return super.initErrorHibernateValidationJSONObject(failResult, validationResult)
            }

            // 验证数据唯一性
            val flag: Boolean = this.validationEditData(role, roleBefore, failResult)
            if (!flag) {
                return super.initErrorValidationJSONObject(failResult)
            }

            // 修改角色 id
            val id: BigInteger? = roleService.updateBackId(editRole)
            return super.initUpdateJSONObject(id)
        } else {
            return super.initErrorRedirectUrl()
        }
    }

    // -------------------------------------------------------------------------------------------------

    /**
     * 查看页面
     *
     * @param id String
     * @param request HttpServletRequest
     * @param redirectAttributes RedirectAttributes
     * @return ModelAndView
     */
    @RequiresPermissions(value = [VIEW_URL])
    @RequestMapping("$VIEW/{id}")
    @RequestLogAnnotation(module = RequestLogConstant.ADMIN_MODULE,
            title = RequestLogConstant.ADMIN_MODULE_ROLE_VIEW)
    @Throws(ControllerException::class)
    fun view(@PathVariable(ID_NAME) id: String, request: HttpServletRequest,
             redirectAttributes: RedirectAttributes): ModelAndView {
        val modelAndView = ModelAndView(super.initView(VIEW_VIEW))
        super.initViewTitleAndModelUrl(VIEW_URL, MODULE_NAME, request)

        val idValue: BigInteger? = super.getId(id)
        // 验证数据
        if (null == idValue || BigInteger.ZERO > idValue) {
            return initValidationResult2Get(modelAndView, redirectAttributes, INDEX_URL)
        }
        // 数据真实性
        val role: Role? = roleService.getById(idValue)
                ?: return initValidationResult2Get(modelAndView, redirectAttributes, INDEX_URL)
        if (null != role) {
            modelAndView.addObject(VIEW_MODEL_NAME, role)
        }

        // 设置上个请求地址
        super.initRefererUrl(request)
        return modelAndView
    }

    // -------------------------------------------------------------------------------------------------

    /**
     * 删除
     * @param request HttpServletRequest
     * @param id String
     * @return JSONObject
     */
    @RequiresPermissions(value = [DELETE_URL])
    @RequestMapping("$DELETE/{id}")
    @ResponseBody
    @RequestLogAnnotation(module = RequestLogConstant.ADMIN_MODULE,
            title = RequestLogConstant.ADMIN_MODULE_ROLE_DELETE)
    @Throws(ControllerException::class)
    fun delete(@PathVariable(ID_NAME) id: String, request: HttpServletRequest): JSONObject? {
        if (super.isAjaxRequest(request)) {
            val idValue: BigInteger? = super.getId(id)
            // 验证数据
            if (null == idValue || BigInteger.ZERO > idValue) {
                super.initErrorCheckJSONObject()
            }
            val role: Role? = roleService.getById(idValue!!)
            if (null == role) {
                super.initErrorCheckJSONObject()
            }
            // 删除 Role id
            val backId: BigInteger? = roleService.removeBackId(role!!.id!!)
            if (null != backId && BigInteger.ZERO < backId) {
                // 异步删除 角色-权限
                controllerAsyncTask.removeByRoleId(backId)
            }
            return super.initDeleteJSONObject(backId)
        }
        return super.initReturnErrorJSONObject()
    }

    // -------------------------------------------------------------------------------------------------

    /**
     * 批量删除
     * @param request HttpServletRequest
     * @return JSONObject
     */
    @RequiresPermissions(value = [DELETE_BATCH_URL])
    @RequestMapping(DELETE_BATCH)
    @ResponseBody
    @RequestLogAnnotation(module = RequestLogConstant.ADMIN_MODULE,
            title = RequestLogConstant.ADMIN_MODULE_ROLE_DELETE_BATCH)
    @Throws(ControllerException::class)
    fun deleteBatch(request: HttpServletRequest): JSONObject? {
        if (super.isAjaxRequest(request)) {
            val idArray: ArrayList<BigInteger>? = super.getIdArray(request)
            // 验证数据
            if (null == idArray || idArray.isEmpty()) {
                super.initErrorCheckJSONObject()
            }
            var flag = false
            if (null != idArray) {
                flag = roleService.removeBatch2UpdateStatus(idArray)!!
            }
            return if (flag) {
                if (null != idArray) {
                    // 异步删除 角色-权限
                    controllerAsyncTask.removeByRoleIdArray(idArray)
                }
                super.initDeleteJSONObject(BigInteger.ONE)
            } else {
                super.initDeleteJSONObject(BigInteger.ZERO)
            }
        }
        return super.initReturnErrorJSONObject()
    }

    // -------------------------------------------------------------------------------------------------

    /**
     * 授权页面
     *
     * @param id String
     * @param request HttpServletRequest
     * @param redirectAttributes RedirectAttributes
     * @return ModelAndView
     */
    @RequiresPermissions(value = [AUTHORIZATION_URL])
    @RequestMapping("$AUTHORIZATION/{id}")
    @RequestLogAnnotation(module = RequestLogConstant.ADMIN_MODULE,
            title = RequestLogConstant.ADMIN_MODULE_ROLE_AUTHORIZATION)
    @FormToken(init = true)
    @Throws(ControllerException::class)
    fun authorization(@PathVariable(ID_NAME) id: String, request: HttpServletRequest,
                      redirectAttributes: RedirectAttributes): ModelAndView {
        val modelAndView = ModelAndView(super.initView(AUTHORIZATION_VIEW))

        super.initViewTitleAndModelUrl(AUTHORIZATION_URL, MODULE_NAME, request)
        val idValue: BigInteger? = super.getId(id)
        if (null == idValue || BigInteger.ZERO > idValue) {
            return initValidationResult2Get(modelAndView, redirectAttributes, INDEX_URL)
        }
        // 数据真实性
        val role: Role? = roleService.getById(idValue)
                ?: return initValidationResult2Get(modelAndView, redirectAttributes, INDEX_URL)
        if (StatusEnum.DELETE.key == role!!.status) {
            return initValidationResult2Get(modelAndView, redirectAttributes, INDEX_URL)
        }

        // 权限 tree 数据
        val currentUser: User? = getCurrentAdmin()
        if (null != currentUser) {
            val currentRole: Role? = roleService.getByUserId(currentUser.id!!)
            if (null != currentRole) {
                // 如果是超级管理员 读取全部权限
                val list: List<Rule>? = if (currentRole.id == BigInteger.ONE) {
                    ruleService.listPidGt0()
                } else {
                    ruleService.list2RoleByRoleIdAndPidGt0(currentRole.id!!)
                }
                if (null != list && list.isNotEmpty()) {
                    request.setAttribute("treeRules", list)
                }
            }
        }

        // 已拥有权限
        val ruleString: String? = ruleService.listIdByRoleId2String(idValue)
        if (null != ruleString) {
            modelAndView.addObject("ruleString", ruleString)
        }
        modelAndView.addObject(VIEW_MODEL_NAME, role)

        // 设置上个请求地址
        super.initRefererUrl(request)
        return modelAndView
    }

    // -------------------------------------------------------------------------------------------------

    /**
     * 保存授权
     *
     * @param request HttpServletRequest
     * @param redirectAttributes RedirectAttributes
     * @return ModelAndView
     */
    @RequiresPermissions(value = [AUTHORIZATION_SAVE_URL])
    @RequestMapping(AUTHORIZATION_SAVE)
    @RequestLogAnnotation(module = RequestLogConstant.ADMIN_MODULE,
            title = RequestLogConstant.ADMIN_MODULE_ROLE_AUTHORIZATION_SAVE)
    @FormToken(remove = true)
    @Throws(ControllerException::class)
    fun authorizationSave(request: HttpServletRequest,
                          redirectAttributes: RedirectAttributes): Any {

        if (httpRequestUtil.isAjaxRequest(request)) {

            val failResult: ResultData = ResultData.fail()
            // 验证数据
            val idValue: BigInteger? = super.getId(request)
            if (null == idValue || BigInteger.ZERO > idValue) {
                super.initErrorCheckJSONObject(failResult)
            }
            // 数据真实性
            val roleBefore: Role? = roleService.getById(idValue!!)
            if (null == roleBefore) {
                super.initErrorCheckJSONObject(failResult)
            }
            if (StatusEnum.DELETE.key == roleBefore!!.status) {
                super.initErrorCheckJSONObject(failResult)
            }


            // 权限数组
            val rulesStr: String? = request.getParameter("rules")
            if (rulesStr == null || rulesStr.isBlank()) {
                return super.initErrorJSONObject(failResult, "message.system.role.authorization.fail")
            }
            val ruleStrArray: List<String> = rulesStr.split(",")
            if (ruleStrArray.isEmpty()) {
                return super.initErrorJSONObject(failResult, "message.system.role.authorization.fail")
            }

            // 转换数组
            val ruleBigIntegerArray: Array<BigInteger>? = ArrayUtil.string2BigIntegerArray(ruleStrArray.toTypedArray())
            if (null != ruleBigIntegerArray && ruleBigIntegerArray.isNotEmpty()) {
                // 排序
                ruleBigIntegerArray.sort()
            } else {
                return super.initErrorJSONObject(failResult, "message.system.role.authorization.fail")
            }


            // 匹配集合
            var flag = false
            // 已拥有权限
            val roleHasRuleString: String? = ruleService.listIdByRoleId2String(idValue)
            var roleHasRuleArray: Array<BigInteger>? = arrayOf()
            if (null != roleHasRuleString) {
                roleHasRuleArray = ArrayUtil.string2BigInteger(roleHasRuleString)!!
                if (roleHasRuleArray.isNotEmpty()) {
                    // 排序
                    roleHasRuleArray.sort()
                    // 比较集合
                    flag = ruleBigIntegerArray.contentEquals(roleHasRuleArray)
                }
            }
            // 权限没有发生变化
            if (flag) {
                val resultData: ResultData = ResultData.ok()
                return super.initSucceedJSONObject(resultData, "message.authorization.succeed")
            } else {
                // 删除已有的权限
                if (null != roleHasRuleArray && roleHasRuleArray.isNotEmpty()) {
                    val hasRules: MutableList<BigInteger> = mutableListOf(BigInteger.ONE)
                    hasRules.addAll(roleHasRuleArray)
                    hasRules.sort()
                    ruleService.removeBatchByRoleIdAndRuleIdArray(idValue, hasRules.toTypedArray())!!
                }
                // 授权的权限集合
                val rules: MutableList<BigInteger> = mutableListOf(BigInteger.ONE)
                rules.addAll(ruleBigIntegerArray)
                rules.sort()
                val result: Int = ruleService.saveBatchByRoleIdAndRuleIdArray(idValue, rules.toTypedArray())!!
                // 授权成功
                return if (0 < result) {
                    // 清空 session 中的用户权限菜单
                    ShiroSessionUtil.setAttribute(configProperties.adminMenuName, null)
                    val resultData: ResultData = ResultData.ok()
                    super.initSucceedJSONObject(resultData, "message.authorization.succeed")
                } else {
                    super.initErrorJSONObject(failResult, "message.authorization.fail")
                }
            }
        } else {
            return super.initErrorRedirectUrl()
        }
    }

    // -------------------------------------------------------------------------------------------------

    /**
     * 回收站页面
     *
     * @param request HttpServletRequest
     * @return ModelAndView
     */
    @RequiresPermissions(value = [RECYCLE_BIN_INDEX_URL])
    @RequestMapping(RECYCLE_BIN_INDEX)
    @RequestLogAnnotation(module = RequestLogConstant.ADMIN_MODULE,
            title = RequestLogConstant.ADMIN_MODULE_ROLE_RECYCLE_BIN_INDEX)
    @Throws(ControllerException::class)
    fun recycleBin(request: HttpServletRequest): ModelAndView {
        val modelAndView = ModelAndView(super.initView(RECYCLE_BIN_INDEX_VIEW))
        super.initViewTitleAndModelUrl(RECYCLE_BIN_INDEX_URL, MODULE_NAME, request)

        val role = Role()
        val title: String? = request.getParameter("title")
        if (null != title && title.isNotBlank()) {
            role.title = title
            modelAndView.addObject("title", title)
        }
        role.status = StatusEnum.DELETE.key
        val page: Page<Role> = roleService.list2page(super.initPage(request), role, Role.ID, false)!!
        modelAndView.addObject(VIEW_PAGE_NAME, page)
        return modelAndView
    }

    // -------------------------------------------------------------------------------------------------

    /**
     * 恢复
     * @param request HttpServletRequest
     * @param id String
     * @return JSONObject
     */
    @RequiresPermissions(value = [RECOVER_URL])
    @RequestMapping("$RECOVER/{id}")
    @ResponseBody
    @RequestLogAnnotation(module = RequestLogConstant.ADMIN_MODULE,
            title = RequestLogConstant.ADMIN_MODULE_ROLE_RECOVER)
    @Throws(ControllerException::class)
    fun recover(@PathVariable(ID_NAME) id: String, request: HttpServletRequest): JSONObject? {
        if (super.isAjaxRequest(request)) {
            val idValue: BigInteger? = super.getId(id)
            // 验证数据
            if (null == idValue || BigInteger.ZERO > idValue) {
                super.initErrorCheckJSONObject()
            }
            val role: Role? = roleService.getById(idValue!!)
            if (null == role) {
                super.initErrorCheckJSONObject()
            }
            // 恢复用户 id
            val backId: BigInteger? = roleService.recoverBackId(role!!.id!!)
            return super.initRecoverJSONObject(backId)
        }
        return super.initReturnErrorJSONObject()
    }

    // -------------------------------------------------------------------------------------------------

    /**
     * 批量恢复
     * @param request HttpServletRequest
     * @return JSONObject
     */
    @RequiresPermissions(value = [RECOVER_BATCH_URL])
    @RequestMapping(RECOVER_BATCH)
    @ResponseBody
    @RequestLogAnnotation(module = RequestLogConstant.ADMIN_MODULE,
            title = RequestLogConstant.ADMIN_MODULE_ROLE_RECOVER_BATCH)
    @Throws(ControllerException::class)
    fun recoverBatch(request: HttpServletRequest): JSONObject? {
        if (super.isAjaxRequest(request)) {
            val idArray: ArrayList<BigInteger>? = super.getIdArray(request)
            // 验证数据
            if (null == idArray || idArray.isEmpty()) {
                super.initErrorCheckJSONObject()
            }
            var flag = false
            if (null != idArray) {
                flag = roleService.recoverBatch2UpdateStatus(idArray)!!
            }
            return if (flag) {
                super.initRecoverJSONObject(BigInteger.ONE)
            } else {
                super.initRecoverJSONObject(BigInteger.ZERO)
            }
        }
        return super.initReturnErrorJSONObject()
    }

    // -------------------------------------------------------------------------------------------------

    /**
     * 验证数据 合法性
     *
     * @param request HttpServletRequest
     * @param role         Role
     * @return Role
     */
    private fun initAddData(request: HttpServletRequest, role: Role): Role {
        val addRole: Role = Role.copy2New(role)
        // ip
        addRole.gmtCreateIp = super.getIp(request)
        // 创建 Role 对象
        return roleService.initSaveRole(addRole)
    }

    // -------------------------------------------------------------------------------------------------

    /**
     * 验证数据 合法性
     *
     * @param role         Role
     * @return Role
     */
    private fun initEditData(role: Role): Role {
        val editRole: Role = role
        // 创建 Role 对象
        return roleService.initEditRole(editRole)
    }

    // -------------------------------------------------------------------------------------------------

    /**
     * 验证数据 数据的唯一性
     *
     * @param role         Role
     * @param failResult ResultData
     * @return Boolean true(通过)/false(未通过)
     */
    private fun validationAddData(role: Role, failResult: ResultData): Boolean {
        val message: String
        // 是否存在
        val titleExist: Role? = roleService.getByTitle(role.title!!.trim().toLowerCase())
        if (null != titleExist) {
            message = localeMessageSourceConfiguration.getMessage(BaseAdminController.MESSAGE_TITLE_EXIST_NAME)
            failResult.setFail()[configProperties.messageName] = message
            return false
        }
        return true
    }

    // -------------------------------------------------------------------------------------------------

    /**
     * 验证数据 数据的唯一性
     *
     * @param role         Role
     * @param failResult ResultData
     * @return Boolean true(通过)/false(未通过)
     */
    private fun validationEditData(newRole: Role, role: Role, failResult: ResultData): Boolean {
        val message: String
        // 是否存在
        val nameExist: Boolean = roleService.propertyUnique(Rule.NAME, newRole.name!!.trim().toLowerCase(),
                role.name!!.toLowerCase())
        if (!nameExist) {
            message = localeMessageSourceConfiguration.getMessage(BaseAdminController.MESSAGE_NAME_EXIST_NAME)
            failResult.setFail()[configProperties.messageName] = message
            return false
        }

        val titleExist: Boolean = roleService.propertyUnique(Rule.TITLE, newRole.title!!.trim().toLowerCase(),
                role.title!!.toLowerCase())
        if (!titleExist) {
            message = localeMessageSourceConfiguration.getMessage(BaseAdminController.MESSAGE_TITLE_EXIST_NAME)
            failResult.setFail()[configProperties.messageName] = message
            return false
        }
        return true
    }

    // -------------------------------------------------------------------------------------------------

}

// -----------------------------------------------------------------------------------------------------

// End RoleController class

/* End of file RoleController.kt */
/* Location: ./src/main/kotlin/wang/encoding/mroot/admin/controller/system/role/RoleController.kt */

// -----------------------------------------------------------------------------------------------------
// +----------------------------------------------------------------------------------------------------
// |                           ErYang出品 属于小极品  O(∩_∩)O~~   共同学习    共同进步
// +----------------------------------------------------------------------------------------------------
// -----------------------------------------------------------------------------------------------------
